<template>
  <div class="container" style="height:86%">

    <base-header ref="baseheader" @onSearch="onSearch" :tabs-name="tabsName" :tag-list="tagList"></base-header>


    <!-- 检索区 -->
    <div class="flex space-between" style="height:90%">
      <div class="tree-list pl5 pt15 pr5 mr12 bgFFF bdradius4" style="width: 290px;overflow: auto;">
        <div class="block">
          <org-structure @search="onTreeSearch"></org-structure>
        </div>
      </div>
      <div class="pl20 pr20 bgFFF bdradius4 btn-section" style="width: calc(100% - 300px)">
        <!-- 表头区 -->
        <div class="flex space-between mt10">
          <div class="flex flex-y-center">
            <button-menu @handleExport="daochu"></button-menu>
          </div>
          <div class="flex flex-y-center"></div>
        </div>
        <!-- 列表区 -->
        <BaseTable
          class="table"
          ref="table"
          :loading="tableLoading"
          v-model="criteria"
          :columns="columns"
          :data="tableData"
          @on-search="loadData"
        >
        </BaseTable>
      </div>
    </div>


    <!--  查看抽屉  -->
    <base-drawers
      v-model="showViewDrawers"
      title="居民信息"
      :showButton="false"
      @input="cancelBt('showViewDrawers')"
    >
      <detail ref="detail" detail-request-name="residentDetail" log-request-name="residentOperatingLog"
              residentType="1" :show-order="false" @labelSaveSuccess="labelSaveSuccess"></detail>
    </base-drawers>
    <!--  编辑抽屉  -->
    <base-drawers
      v-model="showDrawers"
      :title="modalTitle"
      @input="cancelBt('showDrawers')"
      :loading="drawerLoading"
      submitBtn="提交"
      @drawerSubmit="drawerSubmit"
    >
      <div>
        <Form ref="form" :rules="rules" :label-width="105" :model="form">
          <FormItem prop="name" label="居民姓名">
            <Input
              type="text"
              placeholder="请输入居民姓名"
              clearable
              maxlength="20"
              v-model="form.name"
              :disabled="formDisabled"
              style="width: 280px"
            /></FormItem>
          <FormItem prop="tagIdList" label="标签">
            <Select v-model="form.tagIdList" multiple transfer style="width: 280px;" placeholder="请选择标签">
              <OptionGroup :label="item.tagName" v-for="item in tagList" :key="item.id">
                <Option v-for="itemC in item.children" :value="itemC.id" :key="itemC.id">{{ itemC.tagName }}</Option>
              </OptionGroup>
            </Select>
          </FormItem>
          <FormItem prop="idCard" label="身份证号">
            <Input
              type="text"
              placeholder="请输入身份证号"
              maxlength="18"
              clearable
              v-model="form.idCard"
              :disabled="formDisabled"
              style="width: 280px"
            /></FormItem>
          <FormItem prop="phone" label="联系电话">
            <Input
              type="text"
              placeholder="请输入联系电话"
              clearable
              maxlength="11"
              v-model="form.phone"
              style="width: 280px"
            /></FormItem>
        </Form>
      </div>
    </base-drawers>
  </div>
</template>

<script>
import BaseModal from "_c/base-modal"
import BaseHeader from "./components/base-header"
import BaseDrawers from "_c/base-drawers/base-drawers";
import labelInfo from "_c/labelInfo/labelInfo";
import Detail from "../insuredPeople/components/detail";
import FromOne from "@/libs/jss/FormValidation";
import orgStructure from "_c/orgStructure/orgStructure";

export default {
  components: {
    BaseModal,
    BaseHeader,
    BaseDrawers,
    labelInfo,
    Detail,
    orgStructure,
  },
  data() {
    return {
      tabsName: "",
      tagList: [],
      tableLoading: false,
      tableData: [], // 列表绑定数据
      /**
       * 查询条件
       */
      criteria: {
        total: 0,
        page: {
          current: 1,
          size: 10,
        },
      },
      /**
       * 表格字段
       */
      columns: [
        {
          fixed: "left",
          title: "姓名",
          key: "name",
          width: 150,
          align: "left",
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "身份证号",
          key: "idCard",
          align: "left",
          width: 190,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          render: (h, params) => {
            return h("span", {style: {textAlign: "left"}},
              this.commonFn(params.row.idCard, 6, 4)
            );
          },
        },
        {
          title: "联系电话",
          key: "phone",
          align: "left",
          width: 170,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "户籍所在地",
          key: "address",
          align: "left",
          width: 180,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "添加时间",
          key: "createDate",
          align: "left",
          minWidth: 180,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          render: (h, params) => {
            return h(
              "span",
              {style: {textAlign: "left"}},
              this.parseTime(params.row.createDate, "{y}-{m}-{d}")
            );
          },
        },
        {
          title: "来源",
          key: "source",
          align: "left",
          width: 100,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          //  1-主动添加 2-批量导入3-缴费补充
          render: (h, params) => {
            let source = "";
            if (params.row.source == 1) {
              source = "主动添加";
            } else if (params.row.source == 2) {
              source = "批量导入";
            } else if (params.row.source == 3) {
              source = "缴费补充";
            }
            return h(
              "span",
              {style: {textAlign: "left"}},
              source
            );
          },
        },
        {
          title: "标签",
          key: "list",
          align: "left",
          minWidth: 350,
          render: (h, params) => {
            var arr = []
            if (params.row.list) {
              for (let i = 0; i < params.row.list.length; i++) {
                arr.push(params.row.list[i].tagName)
              }
            }
            return (
              <div>
                <labelInfo labelInfo={arr}></labelInfo>
              </div>
            );
          },
        },
      ],
      modalTitle: "",
      //查看
      showViewDrawers: false,
      // 编辑
      showDrawers: false,
      drawerLoading: false,
      form: {},
      formDisabled: false,  // 身份证号、姓名 只读
      form1: {},
      rules: {
        name: [{
          required: true,
          message: "请输入居民姓名",
          trigger: "blur",
        }],
        phone: [{
          required: true,
          message: "请输入正确的电话",
          trigger: "blur",
          validator: FromOne.FormValidate.FormOne().phone,
        }],
        idCard: [{
          required: true,
          message: "请输入正确的身份证号",
          trigger: "blur",
          validator: FromOne.FormValidate.FormOne().id,
        }],
      },
    };
  },
  computed: {},
  watch: {
    $route(val) {
      this.tabsName = this.$route.query.tabsName;
      this.loadData();
    }
  },
  created() {
    let buttonMenu = this.buttonMenu(this.$route.name);
    this.columns.push(this.columnMenu(buttonMenu.buttonRight, this, 180));

    this.tabsName = this.$route.query.tabsName;

    this.getTagList();
  },
  methods: {
    // 导出
    daochu(){
      var data = {
        ...this.criteria,
      };
      var requestName = ''
      if (this.tabsName === "weijiaofeiyibaolist") {
        requestName = "queryForUnpaidInfoForYiExcel";
      } else {
        requestName = "queryForUnpaidInfoexport";
      }
      this.APIS[requestName](data).then((res) => {
        const name = this.tabsName == 'weijiaofeiyibaolist' ? '医保未交费人员列表' : '社保未交费人员列表'
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        var url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", name);
        document.body.appendChild(link);
        link.click();
      })
    },
    onSearch(data) {
      let deptIdSet = this.criteria.deptIdSet;
      this.criteria = data;
      this.criteria.deptIdSet = deptIdSet;
      this.loadData();
    },
    // 获取标签列表
    getTagList() {
      this.APIS.tagList().then((res) => {
        if (res.code == 20000) {
          this.tagList = this.handleTree(res.data);
        } else {
          this.$Message.error(res.message)
        }
      });
    },
    // 初始化获取列表数据
    loadData() {
      this.tableLoading = true;
      let data = {
        ...this.criteria,
      };
      let requestName = "";
      if (this.tabsName === "weijiaofeiyibaolist") {
        requestName = "queryForUnpaidInfoForYi";
      } else {
        requestName = "queryForUnpaidInfo";
      }
      this.APIS[requestName](data).then((res) => {
        this.tableLoading = false;
        if (res.code == 20000) {
          this.criteria.total = res.data.total;
          this.tableData = res.data.records;
        } else {
          this.$Message.error(res.message)
        }
      }).catch(err => {
        this.tableLoading = false;
      });
    },
    onTreeSearch(data) {
      this.criteria.deptIdSet = data.deptIdSet.length ? data.deptIdSet : [data.qywechatDeptId];
      this.criteria.page.current = 1;
      this.criteria.total = 0;
      this.loadData();
    },
    // 查看
    handleView(params) {
      this.showViewDrawers = true;
      this.$refs.detail.getDetail(params);
    },
    // 编辑
    handleEdit(params) {
      // 详情
      this.APIS.residentDetail({id: params.id}).then((res) => {
        if (res.code == 20000) {
          this.form1 = JSON.parse(JSON.stringify(res.data));
          this.form = JSON.parse(JSON.stringify(res.data));
          if (this.form.tagList && this.form.tagList.length) {
            this.form.tagIdList = this.form.tagList.map(item => item.id);
          }
          this.modalTitle = "编辑居民";
          this.drawerLoading = false;
          this.formDisabled = true;
          this.showDrawers = true;
        } else {
          this.$Message.error(res.message)
        }
      });
    },
    //  标签保存成功后加载数据
    labelSaveSuccess(data) {
      this.loadData();
    },
    drawerSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.drawerLoading = true;
          let data = {
            id: this.form.id,
          }
          for (let i in this.form) {
            if (this.form[i] !== this.form1[i]) {
              data[i] = this.form[i];
            }
          }
          this.APIS.residentUpdate(data).then((res) => {
            this.drawerLoading = false;
            if (res.code == 20000) {
              this.$Message.success("编辑成功");
              this.cancelBt('showDrawers');
              this.loadData();
            } else {
              this.$Message.error(res.message)
            }
          });
        }
      });
    },
    // 关闭抽屉
    cancelBt(drawerName) {
      this[drawerName] = false;
      this.form = {};
      this.$refs.form.resetFields();
    },
  },
};
</script>


<style lang="less" scoped>
@import "../setUp/contactsManagement/index";

.table {
  /deep/ .ivu-card-body {
    padding: 0 !important;
  }
}
</style>
